import { createStore } from 'vuex'
import axios from 'axios'

export default createStore({
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    CLEAR_AUTH(state) {
      state.token = ''
      state.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  },
  actions: {
    async login({ commit }, loginData) {
      try {
        const response = await axios.post('/auth/login', loginData)
        const { token, userInfo } = response.data
        commit('SET_TOKEN', token)
        commit('SET_USERINFO', userInfo)
        return response.data
      } catch (error) {
        throw new Error(error.response?.data?.message || '登录失败')
      }
    },
    logout({ commit }) {
      commit('CLEAR_AUTH')
    }
  }
}) 